<template>
  <el-dialog v-model="addReportVisible" :title="noticeId === 0 ? '监控阈值创建' : '监控阈值编辑'" width="1000px">
    <el-form
      ref="formRef"
      style="max-height: 690px; overflow: hidden auto"
      :model="formCustom"
      status-icon
      :rules="rules"
      label-width="auto"
    >
      <div class="title">阈值设置</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="监控模块" prop="module">
            <el-select v-model="formCustom.module" placeholder="请选择" @change="moduleChange">
              <el-option :label="item.name" :value="item.key" :key="index" v-for="(item, index) in moduleList" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="监控对象" prop="monitored">
            <el-select v-model="formCustom.monitored" placeholder="请选择" @change="monitoredChange">
              <el-option :label="item.name" :value="item.key" :key="index" v-for="(item, index) in targetList" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-for="(item, index) in formCustom.conditions" :key="Date.now() + index" prop="conditions" class="condition-cls card2">
        <div class="condition-title">{{ "条件 " + (index + 1) }}</div>
        <div class="condition-close card2" v-if="index !== 0" @click.prevent="removeCondition(index)">
          <el-icon><Close /></el-icon>
        </div>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item
              label="监控指标"
              :prop="'conditions.' + index + '.target'"
              :rules="{
                required: true,
                message: '不能为空',
                trigger: 'blur'
              }"
            >
              <el-select v-model="item.target" placeholder="请选择">
                <el-option :label="a.name" :value="a.key" :key="i" v-for="(a, i) in indexList" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="运算符"
              :prop="'conditions.' + index + '.lookup'"
              :rules="{
                required: true,
                message: '不能为空',
                trigger: 'blur'
              }"
            >
              <el-select v-model="item.lookup" placeholder="请选择">
                <el-option label="=" value="=" />
                <el-option label="≥" value="≥" />
                <el-option label="≤" value="≤" />
                <el-option label="≠" value="≠" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="值"
              :prop="'conditions.' + index + '.value'"
              :rules="{
                required: true,
                message: '不能为空',
                trigger: 'blur'
              }"
            >
              <el-input v-model="item.value" style="width: 90%" min="0" type="number" placeholder="请输入" />&nbsp;%
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item
              label="24h发生次数≥"
              :prop="'conditions.' + index + '.times'"
              :rules="{
                required: true,
                message: '不能为空',
                trigger: 'blur'
              }"
            >
              <el-input v-model="item.times" type="number" min="1" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-form-item>
        <div class="condition-add card2" @click="addCondition()">
          <el-icon style="margin: 0 5px 5px 0"><Plus /></el-icon>
          新增
        </div>
      </el-form-item>
      <div class="title">
        告警设置
        <span class="title-notice">同时触发以上阈值条件将产生综合运行告警</span>
      </div>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="告警类别" prop="alarm_type">
            <el-select v-model="formCustom.alarm_type" placeholder="请选择">
              <el-option :label="item.name" :value="item.key" :key="index" v-for="(item, index) in alarmTypeList" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="告警名称" prop="alarm_name">
            <el-input v-model="formCustom.alarm_name" type="text" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="告警等级" prop="alarm_level">
            <el-select v-model="formCustom.alarm_level" placeholder="请选择">
              <el-option label="重要" value="importance" />
              <el-option label="次要" value="minor" />
              <el-option label="提示" value="note" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重要程度" prop="alarm_degree">
            <el-select v-model="formCustom.alarm_degree" placeholder="请选择">
              <el-option label="重点关注" value="importance" />
              <el-option label="一般关注" value="common" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit(formRef)">确定</el-button>
        <el-button @click="closeDialog()">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddOrEditRole">
import { ref, reactive, onMounted } from "vue";
import {
  createThreshold,
  modifyThreshold,
  getMonitorModule,
  getMonitorObject,
  getMonitorIndex
} from "@/api/modules/monitorManagement/monitorThreshold";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { Plus, Close } from "@element-plus/icons-vue";
import { Threshold } from "@/api/interface/monitorThreshold";
const formRef = ref<FormInstance>();
const moduleList = ref([]) as any;
const targetList = ref([]) as any;
const indexList = ref([]) as any;
const alarmTypeList = ref([]) as any;
let noticeId: any = 0;
const formCustom = reactive({
  module: "",
  monitored: "",
  alarm_level: "",
  alarm_name: "",
  alarm_type: "",
  alarm_degree: "",
  conditions: [
    {
      key: Date.now(),
      target: "",
      lookup: "",
      value: 0,
      times: 1
    }
  ] as Threshold.Condition[]
});
const rules = reactive<FormRules<typeof formCustom>>({
  module: [
    { required: true, message: "不能为空", trigger: "blur" },
    { required: true, message: "长度需为0~64个字符", min: 0, max: 64, trigger: "blur" }
  ],
  alarm_name: [
    { required: true, message: "不能为空", trigger: "blur" },
    { required: true, message: "长度需为0~64个字符", min: 0, max: 64, trigger: "blur" }
  ],
  monitored: [
    { required: true, message: "不能为空", trigger: "blur" },
    { required: true, message: "长度需为0~64个字符", min: 0, max: 64, trigger: "blur" }
  ],
  alarm_level: [{ required: true, message: "不能为空", trigger: "change" }],
  alarm_type: [{ required: true, message: "不能为空", trigger: "change" }],
  alarm_degree: [{ required: true, message: "不能为空", trigger: "change" }]
});
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.org_id 的值，才会触发请求 proTable 数据
let loading = ref<boolean>(false);
const addReportVisible = ref<boolean>(false);
const openDialog = (data?: Threshold.ThresholdList) => {
  addReportVisible.value = true;
  noticeId = data ? data.id : 0;
  if (noticeId && data) {
    Object.assign(formCustom, data);
  } else {
    // 重置表单
    formCustom.module = "";
    formCustom.monitored = "";
    formCustom.alarm_level = "";
    formCustom.alarm_name = "";
    formCustom.alarm_type = "";
    formCustom.conditions = [
      {
        key: Date.now(),
        target: "",
        lookup: "",
        value: 0,
        times: 1
      }
    ];
  }
  loading.value = false;
};
const closeDialog = () => {
  addReportVisible.value = false;
};

const addCondition = () => {
  if (formCustom.conditions.length < 5) {
    formCustom.conditions.push({
      key: Date.now(),
      target: "",
      lookup: "",
      value: 0,
      times: 1
    });
  } else {
    ElMessage({
      type: "warning",
      plain: true,
      message: `最多可添加五组条件!`
    });
  }
};
const removeCondition = (index: number) => {
  formCustom.conditions.splice(index, 1);
};

const getModules = async () => {
  const { data } = await getMonitorModule();
  if (data) {
    moduleList.value = data;
    alarmTypeList.value = data;
  }
};
// emit
const emit = defineEmits<{
  refresh: [];
}>();

const submit = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      if (noticeId === 0) {
        // 创建
        const { data } = await createThreshold(formCustom);
        if (data) {
          ElMessage({
            type: "success",
            message: `操作成功!`
          });
          addReportVisible.value = false;
          // 重置表单
          formCustom.module = "";
          formCustom.monitored = "";
          formCustom.alarm_level = "";
          formCustom.alarm_name = "";
          formCustom.alarm_type = "";
          formCustom.conditions = [
            {
              key: Date.now(),
              target: "",
              lookup: "",
              value: 0,
              times: 1
            }
          ];
          emit("refresh");
        }
      } else {
        const paramsObj = { ...formCustom };
        // 编辑
        const { data } = await modifyThreshold(noticeId, paramsObj);
        if (data) {
          ElMessage({
            type: "success",
            message: `操作成功!`
          });
          addReportVisible.value = false;
          // 重置表单
          formEl?.resetFields();
          emit("refresh");
        }
      }
    } else {
      console.log("error submit!");
    }
  });
};

const moduleChange = async (val: string) => {
  if (val) {
    alarmTypeList.value = [];
    let module_id = moduleList.value[0].id;
    const results = moduleList.value.filter(item => item.key === val);
    if (results.length) {
      module_id = results[0].id;
      alarmTypeList.value = results.map(a => {
        a.name = a.name + "告警";
        return a;
      });
    }
    await getMonitorObject(module_id).then(res => {
      if (res.data) {
        targetList.value = res.data;
      }
    });
  }
};
const monitoredChange = async (val: string) => {
  if (val) {
    let target_id = targetList.value[0].id;
    targetList.value.filter((item: any) => {
      if (item.key === val) {
        target_id = item.id;
      }
    });
    await getMonitorIndex(target_id).then(res => {
      if (res.data) {
        indexList.value = res.data;
      }
    });
  }
};

onMounted(async () => {
  await getModules();
});

defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped>
:deep() .el-dialog .el-dialog__header {
  border-bottom: none !important;
}
:deep() .el-dialog .el-dialog__body {
  max-height: 660px;
  padding: 15px 20px;
  overflow: auto;
}
.filter {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  border: none;
  box-shadow: none;
}
.condition-cls {
  position: relative;
  padding: 20px 20px 0;
  margin-bottom: 10px;
}
.condition-title {
  margin-bottom: 20px;
}
.condition-close {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  padding: 0;
  font-size: 20px;
}
.condition-add {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 32px;
  padding: 0;
  color: var(--el-color-primary);
}
.upload-demo {
  margin-top: 5px;
}
.title {
  padding: 10px;
  margin-bottom: 24px;
  color: var(--el-text-color);
  border-bottom: 1px solid var(--el-border-color);
  .title-notice {
    margin-left: 10px;
    opacity: 0.6;
  }
}
</style>
